import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QFileDialog, QTextEdit, QVBoxLayout, QWidget
import pandas as pd
from utils import extract_and_standardize_date, get_name_money_list

def output(filePath, usename):
        name_list, money_list = get_name_money_list(filePath, usename)
        standard_dates = [extract_and_standardize_date(date) for date in name_list]
        amounts = money_list

        # 构建一个字典来累计每天的金额
        date_amount_sum = {}

        # 假设金额列表与名字日期列表一一对应
        for date, amount in zip(standard_dates, amounts):
            if date is None:
                date = "None"
            if date in date_amount_sum:
                date_amount_sum[date] += amount
            else:
                date_amount_sum[date] = amount

        sum_money = 0
        ans = "日期,金额\n"
        # 按日期排序输出每一天的金额总和
        for date, total_amount in sorted(date_amount_sum.items()):
            total_amount = round(total_amount, 2)
            sum_money += total_amount
            ans += f"{date},{total_amount}\n"
            # print(f"日期 {date} 的总金额为: {total_amount}")

        # 输出总金额合计
        ans += f"总金额,{sum_money}"
        return ans

class ExcelCalculator(QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.initUI()
        
    def initUI(self):
        self.setWindowTitle('Excel 文件计算器')
        self.setGeometry(100, 100, 1200, 600)
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        layout = QVBoxLayout()
        central_widget.setLayout(layout)
        
        # 创建一个按钮，用于打开文件对话框选择Excel文件
        self.openButton = QPushButton('选择Excel文件', self)
        self.openButton.clicked.connect(self.openFile)
        layout.addWidget(self.openButton)
        
        # 创建一个文本区域，用于显示计算结果
        self.textArea = QTextEdit(self)
        self.textArea.setGeometry(50, 100, 1000, 400)
        layout.addWidget(self.textArea)
        
        # 新增：保存结果为CSV的按钮
        self.saveButton = QPushButton('保存结果', self)
        self.saveButton.clicked.connect(self.saveAsExcel)
        layout.addWidget(self.saveButton)
        
        self.show()


    def openFile(self):
        # 打开文件对话框，选择Excel文件
        filePath, _ = QFileDialog.getOpenFileName(self, '选择文件', '', 'Excel Files (*.xlsx *.xls)')
        if filePath:
            try:
                # 使用pandas读取Excel文件
                heji = output(filePath, "合计")
                miwan = output(filePath, "密丸工艺费")
                jianyao = output(filePath, "煎药费")
                aogao = output(filePath, "熬膏费")
                dafen = output(filePath, "打粉加工费")
                baozhuang = output(filePath, "包装费")
                ans = "合计：\n" + heji + "\n密丸工艺费\n" + miwan  + "\n煎药费\n" + jianyao + "\n熬膏费\n" + aogao + "\n打粉加工费\n" + dafen + "\n包装费\n" + baozhuang
                # 显示结果
                self.textArea.setText(ans)
            except Exception as e:
                self.textArea.setText(f"读取文件时发生错误: {str(e)}")
                
    def saveAsExcel(self):
        # 获取文本区域的内容
        text_content = self.textArea.toPlainText()
        
        # 分割文本内容为行，假设每一行都是一个记录
        lines = text_content.split('\n')
        
        # 使用pandas构造DataFrame
        # 注意：此处假设文本区域的内容格式已符合需求，每行按逗号分隔
        try:
            df = pd.DataFrame([line.split(',') for line in lines if line], columns=['Column1', 'Column2'])  # 根据实际情况调整列名
        except Exception as e:
            self.textArea.setText(f"转换为Excel时发生错误: {str(e)}")
            return
        
        # 打开保存文件对话框，并指定保存类型为Excel文件
        filePath, _ = QFileDialog.getSaveFileName(self, '保存Excel文件', '', 'Excel Files (*.xlsx)')
        if filePath:
            try:
                df.to_excel(filePath, index=False)  # 保存为Excel文件
                self.textArea.append("结果已成功保存为Excel文件。")
            except Exception as e:
                self.textArea.setText(f"保存文件时发生错误: {str(e)}")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = ExcelCalculator()
    sys.exit(app.exec_())